import { guid, timeFormat, timeFrom } from 'uview-plus';
// 格式化日期 当天显示小时分钟，七天内显示几天前，超过7天显示年月日
export const DateFormat = (time: string) => {
  const now = new Date();
  const targetDate = new Date(Date.parse(time));

  // 检查是否是同一天
  const isSameDay = now.getFullYear() === targetDate.getFullYear() &&
    now.getMonth() === targetDate.getMonth() &&
    now.getDate() === targetDate.getDate();

  if (isSameDay) {
    return timeFormat(targetDate, 'hh:MM');
  } else {
    const diffTime = Math.abs(now.getTime() - targetDate.getTime());
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays <= 7) {
      return timeFormat(targetDate, 'mm/dd hh:MM');
    } else {
      return timeFormat(targetDate, 'yy/mm/dd');
    }
  }
};


export const captureCover =async (videoPath: string): Promise<string> => {

  // #ifdef MP-WEIXIN || APP-PLUS
  const videoInfo = await uni.getVideoInfo({ src: videoPath });
  const canvasContext = uni.createCanvasContext('videoCoverCanvas');
  canvasContext.drawImage(videoPath, 0, 0, videoInfo.width, videoInfo.height);
  canvasContext.draw();
  const { tempFilePath } = await uni.canvasToTempFilePath({
    canvasId: 'videoCoverCanvas',
    width: videoInfo.width,
    height: videoInfo.height
  });
  return tempFilePath;
  // #endif

  // #ifdef H5
  const videoInfo = await uni.getVideoInfo({ src: videoPath });

  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('无法获取2D绘图上下文');
  }
  canvas.width = videoInfo.width;
  canvas.height = videoInfo.height;
  const video = document.createElement('video');
  video.src = videoPath;
  return  new Promise<void>((resolve) => {
    video.addEventListener('canplaythrough', () => {
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataURL = canvas.toDataURL('image/png');
      resolve(dataURL);
    });
  });
  //#endif
};

